/**
 * This file is released under the GNU General Public License.
 * Refer to the COPYING file distributed with this package.
 *
 * Copyright (c) 2008-2009 WURFL-Pro srl
 */
package net.sourceforge.wurfl.core.handlers.matchers;

import java.util.SortedSet;

import net.sourceforge.wurfl.core.handlers.Handler;
import net.sourceforge.wurfl.core.utils.StringUtils;

import org.apache.commons.lang.text.StrBuilder;

/**
 * @author WURFL-PRO SRL, Rome, Italy
 * @version $Id: SamsungMatcher.java 1045 2009-03-09 15:52:53Z filippo.deluca $
 */
public class SamsungMatcher extends AbstractMatcher {

	public SamsungMatcher(Handler handler) {
		super(handler);
	}

	/**
	 * <p>
	 * If UA starts with one of the following ("SEC-", "SAMSUNG-", "SCH"), apply
	 * default.
	 * </p>
	 * <p>
	 * Else if UA starts with one of the following ("Samsung-","SPH", "SGH" ), apply RIS(FP).
	 * </p>
	 * <p>
	 * Else if UA starts with "SAMSUNG/", apply RIS(SS).
	 * </p>
	 */
	protected String lookForMatchingUserAgent(SortedSet userAgentsSet, String userAgent) {
		
		String match = null;
		
		// RIS(FS)
		if (userAgent.startsWith("SEC-") || userAgent.startsWith("SAMSUNG-") || userAgent.startsWith("SCH")) {
			match = super.lookForMatchingUserAgent(userAgentsSet, userAgent);
		}

		// RIS(FP)
		else if (userAgent.startsWith("Samsung") || userAgent.startsWith("SPH") || userAgent.startsWith("SGH")) {
			int tollerance = StringUtils.firstSpace(userAgent);

			if (logger.isDebugEnabled()) {
				logger.debug("Applying RIS(FP) UA: " + userAgent);
			}
			match = StringUtils.risMatch(userAgentsSet, userAgent, tollerance);
		}
		
		// RIS(SS)
		else if (userAgent.startsWith("SAMSUNG/")) {
			int tollerance = StringUtils.secondSlash(userAgent);

			if (logger.isDebugEnabled()) {
				logger.debug("Applying RIS(SS) UA: " + userAgent);
			}
			match = StringUtils.risMatch(userAgentsSet, userAgent, tollerance);
		}
		
		else if (org.apache.commons.lang.StringUtils.contains(userAgent, "Samsung/SGH-L870")) {
			int tollerance = StringUtils.ordinalIndexOfOrLength(userAgent, "/", 5);

			if (logger.isDebugEnabled()) {
				logger.debug("Applying RIS('/',5) UA: " + userAgent);
			}
			match = StringUtils.risMatch(userAgentsSet, userAgent, tollerance);
		}
		
		// This is an issue
		else if(logger.isWarnEnabled()) {
			StrBuilder logBuilder = new StrBuilder();
			logBuilder.append("The User-Agent: '").append(userAgent).append("' is not handled by Samsung matcher.");
			logger.warn(logBuilder.toString());
		}

		return match;
	}

}
